<template>
  <div class="chat-container">
    <div class="chat-layout">
      <!-- 左侧：用户列表/房间列表 -->
      <div class="chat-sidebar">
        <!-- 客服端：显示统计信息和用户列表 -->
        <template v-if="isKefu">
          <div class="sidebar-header">
            <div class="header-top">
              <h3>用户列表</h3>
              <div class="kefu-status-indicator">
                <span class="status-dot online"></span>
                <span>在线</span>
              </div>
            </div>
            <!-- 统计信息 -->
            <div class="stats-container">
              <div class="stat-item">
                <div class="stat-value">{{ userListStats.total }}</div>
                <div class="stat-label">总用户</div>
              </div>
              <div class="stat-item">
                <div class="stat-value serving">{{ userListStats.serving }}</div>
                <div class="stat-label">服务中</div>
              </div>
              <div class="stat-item">
                <div class="stat-value waiting">{{ userListStats.waiting }}</div>
                <div class="stat-label">待分配</div>
              </div>
            </div>
          </div>
          
          <!-- 筛选标签 -->
          <div class="filter-tabs">
            <button 
              class="filter-tab" 
              :class="{ active: filterType === 'all' }"
              @click="filterType = 'all'"
            >
              全部
            </button>
            <button 
              class="filter-tab" 
              :class="{ active: filterType === 'waiting' }"
              @click="filterType = 'waiting'"
            >
              待分配 <span v-if="userListStats.waiting > 0" class="tab-badge">{{ userListStats.waiting }}</span>
            </button>
            <button 
              class="filter-tab" 
              :class="{ active: filterType === 'serving' }"
              @click="filterType = 'serving'"
            >
              服务中
            </button>
            <button 
              class="filter-tab" 
              :class="{ active: filterType === 'unread' }"
              @click="filterType = 'unread'"
            >
              未读 <span v-if="userListStats.unread > 0" class="tab-badge">{{ userListStats.unread }}</span>
            </button>
          </div>
          
          <!-- 用户列表 -->
          <div class="user-list">
            <div v-if="filteredUserList.length === 0" class="empty-list">
              <div class="empty-icon">📭</div>
              <p>{{ filterType === 'all' ? '暂无用户' : getFilterEmptyText() }}</p>
            </div>
            <div 
              v-for="user in filteredUserList" 
              :key="user.user_id"
              class="user-item"
              :class="{ 
                active: currentRoomId === user.room_id,
                'has-unread': user.unread_count > 0,
                'waiting-assign': !user.kefu_id && filterType !== 'all'
              }"
              @click="selectRoom(user.room_id, user.user_id)"
            >
              <div class="user-avatar" :class="{ 'has-status': user.kefu_id }">
                <img v-if="user.avatar" :src="user.avatar" alt="" />
                <span v-else>{{ user.username?.charAt(0) || 'U' }}</span>
                <span v-if="user.kefu_id" class="avatar-status online"></span>
              </div>
              <div class="user-info">
                <div class="user-name-row">
                  <span class="user-name">{{ user.nickname || user.username || `用户${user.user_id}` }}</span>
                  <span v-if="!user.kefu_id" class="user-status-tag waiting">待分配</span>
                  <span v-else class="user-status-tag serving">服务中</span>
                </div>
                <div class="user-last-message">
                  {{ user.last_message?.content?.substring(0, 25) || '暂无消息' }}
                </div>
                <div v-if="user.last_message?.created_at" class="user-last-time">
                  {{ formatRelativeTime(user.last_message.created_at) }}
                </div>
              </div>
              <div v-if="user.unread_count > 0" class="unread-badge">{{ user.unread_count > 99 ? '99+' : user.unread_count }}</div>
            </div>
          </div>
        </template>
        
        <!-- 用户端：显示房间信息 -->
        <template v-else>
          <div class="sidebar-header">
            <h3>聊天</h3>
          </div>
          <div class="room-list">
            <div class="room-info-card">
              <div class="card-header">
              <h4>{{ roomType === 'merchant' ? '商家客服' : '人工客服' }}</h4>
              <div class="chat-status">
                <span :class="wsConnected ? 'status-online' : 'status-offline'"></span>
                <span>{{ wsConnected ? '已连接' : '连接中...' }}</span>
              </div>
            </div>
            <div v-if="currentRoom" class="room-status">
              <div v-if="roomType === 'merchant'" class="status-item success">
                <span class="status-icon">💬</span>
                <span>商家在线</span>
              </div>
              <div v-else-if="currentRoom.kefu_id" class="status-item success">
                <span class="status-icon">✓</span>
                <span>已分配客服</span>
              </div>
              <div v-else class="status-item waiting">
                <span class="status-icon">⏳</span>
                <span>等待分配客服中...</span>
              </div>
            </div>
            <div v-if="!wsConnected" class="reconnect-tip">
              <p>正在连接客服系统，请稍候...</p>
            </div>
            </div>
          </div>
        </template>
      </div>
      
      <!-- 右侧：聊天窗口 -->
      <div class="chat-main">
        <div v-if="!currentRoomId" class="chat-empty">
          <div class="empty-content">
            <div class="empty-icon">💬</div>
            <p v-if="isKefu">请选择一个用户开始对话</p>
            <p v-else-if="wsConnected">等待分配客服中，请稍候...</p>
            <p v-else>连接中，即将为您分配客服...</p>
          </div>
        </div>
        
        <div v-else class="chat-window">
          <!-- 聊天头部 -->
          <div class="chat-header">
            <div class="header-info">
              <div class="header-title-row">
                <h4>{{ currentUserName || (isKefu ? '用户' : (roomType === 'merchant' ? '商家' : '客服')) }}</h4>
                <div class="header-status">
                  <span v-if="roomType === 'merchant'" class="status-dot-small online"></span>
                  <span v-else-if="isKefu" class="status-dot-small online"></span>
                  <span v-else-if="!isKefu && !currentRoom?.kefu_id" class="status-dot-small waiting"></span>
                  <span v-else-if="!isKefu && currentRoom?.kefu_id" class="status-dot-small online"></span>
                  <span v-else class="status-dot-small online"></span>
                  <span v-if="roomType === 'merchant'" class="status-text online-text">商家在线</span>
                  <span v-else-if="isKefu" class="status-text online-text">服务中</span>
                  <span v-else-if="!isKefu && !currentRoom?.kefu_id" class="status-text waiting-text">等待客服接入</span>
                  <span v-else-if="!isKefu && currentRoom?.kefu_id" class="status-text online-text">客服在线</span>
                  <span v-else class="status-text online-text">服务中</span>
                </div>
              </div>
              <div v-if="isKefu && currentRoomId" class="header-meta">
                <span class="meta-item">房间ID: {{ currentRoomId }}</span>
                <span v-if="currentUserId" class="meta-item">用户ID: {{ currentUserId }}</span>
              </div>
            </div>
            <div class="header-actions">
              <button v-if="isKefu && !currentRoom?.kefu_id && roomType !== 'merchant'" @click="assignToMe" class="btn-assign">
                <span class="btn-icon">✓</span>
                分配给我
              </button>
              <button v-if="isPlatformKefu && currentRoomId && roomType !== 'merchant'" @click="deleteRoom" class="btn-delete">
                <span class="btn-icon">🗑️</span>
                删除房间
              </button>
              <div v-if="isKefu" class="kefu-badge">
                <span class="badge-icon">👤</span>
                平台客服
              </div>
            </div>
          </div>
          
          <!-- 消息列表 -->
          <div class="messages-container" ref="messagesContainer">
            <div 
              v-for="message in messages" 
              :key="message.id"
              class="message-item"
              :class="{ 'message-sent': message.sender_type === (isKefu ? 'kefu' : (roomType === 'merchant' ? 'merchant' : 'user')), 'message-received': message.sender_type !== (isKefu ? 'kefu' : (roomType === 'merchant' ? 'merchant' : 'user')) }"
            >
              <div class="message-content">
                <div class="message-text">{{ message.content }}</div>
                <div class="message-time">{{ formatTime(message.created_at) }}</div>
              </div>
            </div>
          </div>
          
          <!-- 输入框 -->
          <div class="chat-input">
            <div v-if="!isKefu && !currentRoom?.kefu_id && wsConnected" class="waiting-notice">
              <span>💡 客服尚未接入，消息已保存，客服接入后即可看到</span>
            </div>
            <div v-if="isKefu" class="kefu-input-notice">
              <span>✓ 您正在以平台客服身份为用户提供服务</span>
            </div>
            <input 
              v-model="inputMessage" 
              @keyup.enter="sendMessage"
              :placeholder="!wsConnected ? '连接中...' : (isKefu || currentRoom?.kefu_id ? '输入消息...' : '输入消息（客服接入后可看到）...')"
              :disabled="!wsConnected"
            />
            <button 
              @click="sendMessage" 
              :disabled="!wsConnected || !inputMessage.trim()"
            >
              发送
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, computed } from 'vue'
import { chatAPI, authAPI } from '../api/index'
import { useRouter, useRoute } from 'vue-router'

export default {
  name: 'Chat',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const messagesContainer = ref(null)
    const currentRoomId = ref(null)
    const currentUserId = ref(null)
    const currentUserName = ref('')
    const currentRoom = ref(null)
    const messages = ref([])
    const inputMessage = ref('')
    const wsConnected = ref(false)
    const ws = ref(null)
    const isConnecting = ref(false) // 是否正在连接中，避免重复连接
    const reconnectTimer = ref(null) // 重连定时器
    const userList = ref([])
    const isKefu = ref(false)
    const isPlatformKefu = ref(false) // 是否为平台客服
    const kefuAssigned = ref(false) // 是否已分配客服
    const roomType = ref('kefu') // 房间类型：kefu(客服)或merchant(商户)
    const filterType = ref('all') // 筛选类型：all, waiting, serving, unread
    
    // 获取用户信息判断是否为客服
    const checkUserRole = async () => {
      try {
        // 优先从API获取最新用户信息（包含role_code）
        let userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        
        // 尝试从API获取最新用户信息
        try {
          const latestUserInfo = await authAPI.getCurrentUser()
          if (latestUserInfo) {
            userInfo = latestUserInfo
            // 更新localStorage中的用户信息
            localStorage.setItem('userInfo', JSON.stringify(latestUserInfo))
          }
        } catch (apiError) {
          console.warn('获取最新用户信息失败，使用缓存:', apiError)
        }
        
        // 检查角色代码：platform_kefu 或 kefu 都视为客服
        // role_code 是字符串，role 可能是对象，需要统一处理
        let roleCode = userInfo.role_code
        if (!roleCode && userInfo.role) {
          // 如果 role_code 不存在，尝试从 role 对象获取
          roleCode = typeof userInfo.role === 'string' ? userInfo.role : userInfo.role.code
        }
        
        // 判断是否为客服：platform_kefu 或 kefu 都视为客服
        isKefu.value = roleCode === 'platform_kefu' || roleCode === 'kefu'
        // 判断是否为平台客服（只有platform_kefu才是平台客服）
        isPlatformKefu.value = roleCode === 'platform_kefu'
        
        console.log('用户角色检查:', { 
          roleCode, 
          isKefu: isKefu.value,
          isPlatformKefu: isPlatformKefu.value,
          userId: userInfo.id,
          username: userInfo.username,
          role_id: userInfo.role_id,
          fullUserInfo: userInfo
        })
        
        if (isKefu.value) {
          console.log('✅ 已识别为客服身份，将进入客服模式')
        } else {
          console.log('ℹ️ 普通用户身份，将进入用户模式')
        }
      } catch (e) {
        console.error('获取用户信息失败:', e)
      }
    }
    
    // 关闭WebSocket连接
    const closeWebSocket = () => {
      // 清除重连定时器
      if (reconnectTimer.value) {
        clearTimeout(reconnectTimer.value)
        reconnectTimer.value = null
      }
      
      // 关闭现有连接
      if (ws.value) {
        // 移除事件监听器，避免触发重连
        ws.value.onopen = null
        ws.value.onmessage = null
        ws.value.onerror = null
        ws.value.onclose = null
        
        // 如果连接还未关闭，先关闭它
        if (ws.value.readyState === WebSocket.OPEN || ws.value.readyState === WebSocket.CONNECTING) {
          ws.value.close()
        }
        ws.value = null
      }
      
      wsConnected.value = false
      isConnecting.value = false
    }
    
    // 初始化WebSocket连接
    const initWebSocket = () => {
      console.log('🔌 initWebSocket 被调用', {
        isConnecting: isConnecting.value,
        wsExists: !!ws.value,
        wsReadyState: ws.value ? ws.value.readyState : 'N/A',
        wsConnected: wsConnected.value,
        isKefu: isKefu.value
      })
      
      // 如果正在连接中，不重复连接
      if (isConnecting.value) {
        console.log('⚠️ WebSocket正在连接中，跳过重复连接')
        return
      }
      
      // 如果已有连接且状态正常，不重复连接
      if (ws.value && (ws.value.readyState === WebSocket.OPEN || ws.value.readyState === WebSocket.CONNECTING)) {
        console.log('⚠️ WebSocket已连接或正在连接，跳过重复连接', {
          readyState: ws.value.readyState,
          OPEN: WebSocket.OPEN,
          CONNECTING: WebSocket.CONNECTING,
          url: ws.value.url
        })
        // 如果连接已打开但 wsConnected 为 false，更新状态
        if (ws.value.readyState === WebSocket.OPEN && !wsConnected.value) {
          console.log('⚠️ 检测到连接已打开但状态未更新，修复状态')
          wsConnected.value = true
        }
        return
      }
      
      try {
        // 先关闭旧连接
        closeWebSocket()
        
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        const userId = userInfo.id
        if (!userId) {
          router.push('/login')
          return
        }
        
        currentUserId.value = userId
        isConnecting.value = true
        
        const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
        const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
        const wsHost = import.meta.env.VITE_WS_BASE_URL || baseURL.replace('http://', '').replace('https://', '')
        const wsUrl = isKefu.value 
          ? `${wsProtocol}//${wsHost}/api/chat/ws/kefu/${userId}`
          : `${wsProtocol}//${wsHost}/api/chat/ws/user/${userId}`
        
        console.log('创建新的WebSocket连接:', wsUrl, 'isKefu:', isKefu.value)
        
        ws.value = new WebSocket(wsUrl)
        
        ws.value.onopen = () => {
          wsConnected.value = true
          isConnecting.value = false
          console.log('✅ WebSocket连接成功:', wsUrl)
          console.log('✅ WebSocket状态:', {
            readyState: ws.value.readyState,
            OPEN: WebSocket.OPEN,
            wsConnected: wsConnected.value,
            currentRoomId: currentRoomId.value,
            isKefu: isKefu.value
          })
        }
        
        ws.value.onmessage = (event) => {
          try {
            const data = JSON.parse(event.data)
            handleWebSocketMessage(data)
          } catch (e) {
            console.error('解析WebSocket消息失败:', e)
          }
        }
        
        ws.value.onerror = (error) => {
          console.error('❌ WebSocket错误:', error)
          wsConnected.value = false
          isConnecting.value = false
        }
        
        ws.value.onclose = (event) => {
          wsConnected.value = false
          isConnecting.value = false
          console.log('WebSocket连接关闭:', {
            code: event.code,
            reason: event.reason,
            wasClean: event.wasClean
          })
          
          // 只有在非正常关闭时才重连（排除手动关闭的情况）
          // 清除旧的重连定时器
          if (reconnectTimer.value) {
            clearTimeout(reconnectTimer.value)
          }
          
          // 3秒后尝试重连（只有在连接真正关闭时）
          reconnectTimer.value = setTimeout(() => {
            if (!ws.value || ws.value.readyState === WebSocket.CLOSED) {
              console.log('尝试重新连接WebSocket...')
              initWebSocket()
            }
          }, 3000)
        }
      } catch (e) {
        console.error('初始化WebSocket失败:', e)
        isConnecting.value = false
        wsConnected.value = false
      }
    }
    
    // 处理WebSocket消息
    const handleWebSocketMessage = (data) => {
      if (data.type === 'connected') {
        console.log('连接成功:', data.message)
        if (data.room_id && !isKefu.value) {
          // 用户端连接成功，设置房间ID
          currentRoomId.value = data.room_id
          loadRoomInfo()
          // 连接成功后加载历史消息
          loadMessages()
        }
      } else if (data.type === 'message') {
        // 收到新消息
        const message = data.data || data
        console.log('收到消息:', message, '当前房间ID:', currentRoomId.value, '消息类型:', message.sender_type)
        
        // 检查消息是否属于当前房间
        // 使用字符串比较，确保类型一致
        const messageRoomId = String(message.room_id || '')
        const currentRoomIdStr = String(currentRoomId.value || '')
        
        if (messageRoomId === currentRoomIdStr) {
          // 检查是否已存在（避免重复）
          const exists = messages.value.some(m => m.id === message.id)
          if (!exists) {
            console.log('添加消息到列表:', message)
            messages.value.push(message)
            // 重新排序确保消息按时间正序排列
            messages.value = sortMessages(messages.value)
            scrollToBottom()
          } else {
            console.log('消息已存在，跳过:', message.id)
          }
        } else {
          // 消息不属于当前房间
          if (isKefu.value) {
            // 客服端：收到其他房间的消息（可能是从通知房间收到的）
            // 刷新用户列表，以便显示新消息提示
            console.log('客服收到其他房间的消息，刷新用户列表', {
              messageRoomId,
              currentRoomIdStr,
              senderType: message.sender_type
            })
            loadUserList()
            
            // 如果当前没有选中房间，自动切换到该用户的房间
            if (!currentRoomId.value && messageRoomId) {
              // 从room_id中提取user_id（格式：chat_room_{user_id}）
              const userIdMatch = messageRoomId.match(/chat_room_(\d+)/)
              if (userIdMatch) {
                const userId = parseInt(userIdMatch[1])
                console.log('自动切换到用户房间:', messageRoomId, userId)
                selectRoom(messageRoomId, userId)
              }
            }
          } else {
            console.warn('消息不匹配当前房间，跳过显示', {
              messageRoomId,
              currentRoomIdStr,
              senderType: message.sender_type,
              messageContent: message.content
            })
          }
        }
      } else if (data.type === 'new_user' && isKefu.value) {
        // 客服收到新用户通知
        loadUserList()
      } else if (data.type === 'kefu_assigned' && !isKefu.value) {
        // 用户收到客服分配通知
        kefuAssigned.value = true
        if (data.data && data.data.kefu_id) {
          if (currentRoom.value) {
            currentRoom.value.kefu_id = data.data.kefu_id
          }
          loadRoomInfo()
        }
      } else if (data.type === 'error') {
        console.error('WebSocket错误:', data.message)
        alert(`错误: ${data.message}`)
      } else if (data.type === 'joined_room') {
        // 成功加入房间
        console.log('已加入房间:', data.room_id)
      }
    }
    
    // 发送消息
    const sendMessage = async () => {
      console.log('🔍 发送消息检查:', {
        hasMessage: !!inputMessage.value.trim(),
        messageContent: inputMessage.value.trim(),
        wsConnected: wsConnected.value,
        currentRoomId: currentRoomId.value,
        wsExists: !!ws.value,
        wsReadyState: ws.value ? ws.value.readyState : 'N/A',
        wsReadyStateText: ws.value ? (ws.value.readyState === WebSocket.OPEN ? 'OPEN' : ws.value.readyState === WebSocket.CONNECTING ? 'CONNECTING' : ws.value.readyState === WebSocket.CLOSING ? 'CLOSING' : ws.value.readyState === WebSocket.CLOSED ? 'CLOSED' : 'UNKNOWN') : 'N/A',
        isKefu: isKefu.value
      })
      
      if (!inputMessage.value.trim()) {
        console.warn('❌ 消息内容为空')
        return
      }
      
      if (!wsConnected.value) {
        console.warn('❌ WebSocket未连接 (wsConnected.value = false)')
        return
      }
      
      if (!currentRoomId.value) {
        console.warn('❌ 当前房间ID为空 (currentRoomId.value =', currentRoomId.value, ')')
        return
      }
      
      // 如果用户端且未分配客服，仍然允许发送（消息会保存，等客服接入后可以看到）
      if (!isKefu.value && !currentRoom.value?.kefu_id) {
        // 提示用户，但仍可发送
        console.log('客服尚未接入，消息已保存')
      }
      
      // 如果是客服且还没有加入用户房间，先加入房间
      if (isKefu.value && ws.value && ws.value.readyState === WebSocket.OPEN) {
        // 确保已加入房间（join_user_room会在selectRoom中调用，但这里再确认一次）
        console.log('准备发送消息到房间:', currentRoomId.value)
      }
      
      // 检查WebSocket连接状态
      if (!ws.value) {
        console.error('❌ WebSocket实例不存在')
        alert('WebSocket未初始化，请刷新页面重试')
        return
      }
      
      const readyState = ws.value.readyState
      if (readyState !== WebSocket.OPEN) {
        const stateText = readyState === WebSocket.CONNECTING ? 'CONNECTING' 
          : readyState === WebSocket.CLOSING ? 'CLOSING'
          : readyState === WebSocket.CLOSED ? 'CLOSED'
          : 'UNKNOWN'
        console.error('❌ WebSocket未连接，无法发送消息', {
          readyState: readyState,
          stateText: stateText,
          OPEN: WebSocket.OPEN,
          wsConnected: wsConnected.value
        })
        alert(`WebSocket未连接 (${stateText})，请等待连接建立后重试`)
        return
      }
      
      const message = {
        action: 'send_message',
        content: inputMessage.value.trim(),
        room_id: currentRoomId.value
      }
      
      try {
        console.log('📤 发送消息:', message)
        console.log('📤 WebSocket状态确认:', {
          readyState: ws.value.readyState,
          OPEN: WebSocket.OPEN,
          url: ws.value.url
        })
        ws.value.send(JSON.stringify(message))
        const sentContent = inputMessage.value.trim()
        inputMessage.value = ''
        console.log('✅ 消息已发送:', sentContent)
        // 消息发送后，WebSocket会收到服务器返回的消息，会自动添加到列表并排序
      } catch (error) {
        console.error('❌ 发送消息失败:', error)
        console.error('❌ 错误详情:', {
          message: error.message,
          stack: error.stack,
          wsReadyState: ws.value?.readyState
        })
        alert('发送消息失败: ' + error.message)
      }
    }
    
    // 选择房间
    const selectRoom = async (roomId, userId) => {
      console.log('🏠 选择房间:', { roomId, userId, currentRoomId: currentRoomId.value, isKefu: isKefu.value })
      
      if (currentRoomId.value === roomId) {
        console.log('⚠️ 房间已选中，跳过')
        return
      }
      
      // 清空当前消息列表
      messages.value = []
      currentRoomId.value = roomId
      currentUserId.value = userId
      console.log('✅ 房间ID已设置:', currentRoomId.value)
      
      // 如果是客服，需要加入用户房间并获取房间信息
      if (isKefu.value && ws.value && ws.value.readyState === WebSocket.OPEN) {
        console.log('📤 客服加入用户房间:', roomId)
        ws.value.send(JSON.stringify({
          action: 'join_user_room',
          room_id: roomId
        }))
        
        // 从用户列表获取房间信息
        const user = userList.value.find(u => u.user_id === userId || u.room_id === roomId)
        if (user) {
          currentUserName.value = user.nickname || user.username || `用户${userId}`
          // 更新当前房间信息
          currentRoom.value = {
            room_id: roomId,
            user_id: userId,
            kefu_id: null, // 从API获取真实值
            is_active: true
          }
        }
      }
      
      // 加载历史消息
      await loadMessages()
      
      // 获取用户信息
      if (isKefu.value) {
        const user = userList.value.find(u => u.user_id === userId || u.room_id === roomId)
        if (user) {
          currentUserName.value = user.nickname || user.username || `用户${userId}`
        }
      }
    }
    
    // 加载房间信息
    const loadRoomInfo = async () => {
      if (!currentRoomId.value || isKefu.value) return
      
      try {
        // 获取用户房间信息
        const roomData = await chatAPI.getMyRoom()
        if (roomData) {
          currentRoom.value = {
            room_id: roomData.room_id,
            user_id: roomData.user_id,
            kefu_id: roomData.kefu_id,
            is_active: roomData.is_active
          }
          if (roomData.kefu_id) {
            kefuAssigned.value = true
            currentUserName.value = '客服'
          }
        }
      } catch (e) {
        console.error('加载房间信息失败:', e)
        // 如果API不存在，使用默认值
        if (!currentRoom.value && currentRoomId.value) {
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
          currentRoom.value = {
            room_id: currentRoomId.value,
            user_id: userInfo.id,
            kefu_id: null,
            is_active: true
          }
        }
      }
    }
    
    // 对消息按时间排序（正序：旧的在上，新的在下）
    const sortMessages = (msgList) => {
      return [...msgList].sort((a, b) => {
        const timeA = new Date(a.created_at || a.timestamp || 0).getTime()
        const timeB = new Date(b.created_at || b.timestamp || 0).getTime()
        return timeA - timeB
      })
    }
    
    // 加载历史消息
    const loadMessages = async () => {
      if (!currentRoomId.value) return
      
      try {
        const data = await chatAPI.getMessages(currentRoomId.value)
        // 确保消息按时间正序排序（旧的在上，新的在下）
        messages.value = sortMessages(data || [])
        await nextTick()
        scrollToBottom()
      } catch (e) {
        console.error('加载消息失败:', e)
      }
    }
    
    // 加载用户列表（客服端）
    const loadUserList = async () => {
      if (!isKefu.value) return
      
      try {
        const data = await chatAPI.getUsers()
        userList.value = data || []
        
        // 如果当前没有选中房间，自动选中第一个
        if (!currentRoomId.value && userList.value.length > 0) {
          const firstUser = userList.value[0]
          selectRoom(firstUser.room_id, firstUser.user_id)
        }
      } catch (e) {
        console.error('加载用户列表失败:', e)
      }
    }
    
    // 分配客服
    const assignToMe = async () => {
      if (!currentRoomId.value) return
      
      try {
        await chatAPI.assignKefu(currentRoomId.value)
        // 更新房间信息
        if (currentRoom.value) {
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
          currentRoom.value.kefu_id = userInfo.id
        }
        // 重新加载用户列表
        await loadUserList()
        // 加入房间
        if (ws.value && ws.value.readyState === WebSocket.OPEN) {
          ws.value.send(JSON.stringify({
            action: 'join_user_room',
            room_id: currentRoomId.value
          }))
        }
      } catch (e) {
        console.error('分配客服失败:', e)
        alert('分配失败，请重试')
      }
    }
    
    // 删除房间（仅平台客服可用）
    const deleteRoom = async () => {
      if (!currentRoomId.value) return
      
      // 确认删除
      if (!confirm('确定要删除这个房间吗？删除后房间将被标记为不活跃，用户将无法继续在此房间发送消息。')) {
        return
      }
      
      const roomIdToDelete = currentRoomId.value
      
      try {
        await chatAPI.deleteRoom(roomIdToDelete)
        alert('房间已删除')
        
        // 如果WebSocket已连接，发送离开房间的消息
        if (ws.value && ws.value.readyState === WebSocket.OPEN) {
          ws.value.send(JSON.stringify({
            action: 'leave_room',
            room_id: roomIdToDelete
          }))
        }
        
        // 清空当前房间信息
        currentRoomId.value = null
        currentRoom.value = null
        currentUserId.value = null
        messages.value = []
        
        // 重新加载用户列表
        await loadUserList()
      } catch (e) {
        console.error('删除房间失败:', e)
        const errorMsg = e.response?.data?.detail || e.message || '删除失败，请重试'
        alert(errorMsg)
      }
    }
    
    // 滚动到底部
    const scrollToBottom = () => {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
        }
      })
    }
    
    // 格式化时间
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const now = new Date()
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
      
      if (date >= today) {
        return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
      } else {
        return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
      }
    }
    
    // 格式化相对时间
    const formatRelativeTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      const now = new Date()
      const diff = now - date
      const seconds = Math.floor(diff / 1000)
      const minutes = Math.floor(seconds / 60)
      const hours = Math.floor(minutes / 60)
      const days = Math.floor(hours / 24)
      
      if (days > 0) {
        return `${days}天前`
      } else if (hours > 0) {
        return `${hours}小时前`
      } else if (minutes > 0) {
        return `${minutes}分钟前`
      } else {
        return '刚刚'
      }
    }
    
    // 用户列表统计
    const userListStats = computed(() => {
      const total = userList.value.length
      const serving = userList.value.filter(u => u.kefu_id).length
      const waiting = userList.value.filter(u => !u.kefu_id).length
      const unread = userList.value.filter(u => u.unread_count > 0).length
      return { total, serving, waiting, unread }
    })
    
    // 筛选后的用户列表
    const filteredUserList = computed(() => {
      if (filterType.value === 'all') {
        return userList.value
      } else if (filterType.value === 'waiting') {
        return userList.value.filter(u => !u.kefu_id)
      } else if (filterType.value === 'serving') {
        return userList.value.filter(u => u.kefu_id)
      } else if (filterType.value === 'unread') {
        return userList.value.filter(u => u.unread_count > 0)
      }
      return userList.value
    })
    
    // 获取筛选空状态文本
    const getFilterEmptyText = () => {
      if (filterType.value === 'waiting') {
        return '暂无待分配用户'
      } else if (filterType.value === 'serving') {
        return '暂无服务中用户'
      } else if (filterType.value === 'unread') {
        return '暂无未读消息'
      }
      return '暂无数据'
    }
    
    onMounted(async () => {
      // 先检查用户角色，确保 isKefu 正确设置
      await checkUserRole()
      
      console.log('页面初始化完成，isKefu =', isKefu.value)
      
      // 检查路由参数，判断是否为商户聊天
      const queryRoomId = route.query.room_id
      const queryRoomType = route.query.room_type
      
      if (queryRoomId && queryRoomType === 'merchant') {
        // 商户聊天模式
        roomType.value = 'merchant'
        currentRoomId.value = queryRoomId
        currentUserName.value = '商家'
        
        // 加载商户聊天房间信息和历史消息
        try {
          // 商户聊天房间已创建，直接加载消息
          await loadMessages()
          
          // 设置房间信息
          const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
          currentUserId.value = userInfo.id
          currentRoom.value = {
            room_id: queryRoomId,
            user_id: userInfo.id,
            room_type: 'merchant',
            merchant_id: route.query.merchant_id || null,
            attraction_id: route.query.attraction_id || null,
            order_id: route.query.order_id || null
          }
        } catch (e) {
          console.error('加载商户聊天房间失败:', e)
        }
        
        // 初始化WebSocket（使用用户端WebSocket）
        initWebSocket()
      } else if (isKefu.value) {
        // 客服端：平台客服登录后直接进入客服模式
        console.log('✅ 进入客服模式，初始化客服界面')
        console.log('准备连接客服WebSocket...')
        initWebSocket()
        // 延迟加载用户列表，确保WebSocket连接成功
        setTimeout(async () => {
          console.log('开始加载用户列表...')
          await loadUserList()
        }, 500)
      } else {
        // 用户端：客服聊天模式
        console.log('ℹ️ 进入用户模式，初始化用户聊天界面')
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        if (userInfo.id) {
          const roomId = `user${userInfo.id}`
          currentRoomId.value = roomId
          currentUserId.value = userInfo.id
          currentUserName.value = '客服'
          
          // 加载房间信息（包括客服分配状态）
          await loadRoomInfo()
          
          // 初始化WebSocket
          initWebSocket()
        }
      }
    })
    
    onUnmounted(() => {
      // 组件卸载时，彻底关闭WebSocket连接
      closeWebSocket()
    })
    
      return {
      messagesContainer,
      currentRoomId,
      currentUserName,
      currentRoom,
      messages,
      inputMessage,
      wsConnected,
      userList,
      isKefu,
      isPlatformKefu,
      kefuAssigned,
      roomType,
      filterType,
      userListStats,
      filteredUserList,
      sendMessage,
      selectRoom,
      assignToMe,
      deleteRoom,
      formatTime,
      formatRelativeTime,
      getFilterEmptyText,
      loadRoomInfo
    }
  }
}
</script>

<style scoped>
.chat-container {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.chat-layout {
  display: flex;
  height: 100%;
  border: 1px solid #e0e0e0;
}

.chat-sidebar {
  width: 300px;
  border-right: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e0e0e0;
  background: white;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.kefu-status-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.status-dot.online {
  background: #4caf50;
  box-shadow: 0 0 4px rgba(76, 175, 80, 0.5);
}

.stats-container {
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 6px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #2196f3;
  margin-bottom: 4px;
}

.stat-value.serving {
  color: #4caf50;
}

.stat-value.waiting {
  color: #ff9800;
}

.stat-label {
  font-size: 11px;
  color: #666;
}

.filter-tabs {
  display: flex;
  padding: 8px;
  gap: 4px;
  background: white;
  border-bottom: 1px solid #e0e0e0;
  overflow-x: auto;
}

.filter-tab {
  flex: 1;
  padding: 6px 12px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  transition: all 0.2s;
  position: relative;
}

.filter-tab:hover {
  background: #f5f5f5;
}

.filter-tab.active {
  background: #2196f3;
  color: white;
}

.tab-badge {
  display: inline-block;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 10px;
  padding: 1px 6px;
  font-size: 10px;
  margin-left: 4px;
}

.filter-tab.active .tab-badge {
  background: rgba(255, 255, 255, 0.25);
}

.empty-list {
  padding: 40px 20px;
  text-align: center;
  color: #999;
}

.empty-list .empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
  opacity: 0.5;
}

.empty-list p {
  margin: 0;
  font-size: 14px;
}

.user-list, .room-list {
  flex: 1;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid #e0e0e0;
  background: white;
  transition: background 0.2s;
}

.user-item:hover {
  background: #f0f0f0;
}

.user-item.active {
  background: #e3f2fd;
  border-left: 3px solid #2196f3;
}

.user-item.has-unread {
  background: #fff3e0;
}

.user-item.has-unread.active {
  background: #e3f2fd;
}

.user-item.waiting-assign {
  border-left: 3px solid #ff9800;
}

.user-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background: #2196f3;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-weight: bold;
  position: relative;
  flex-shrink: 0;
}

.user-avatar.has-status::after {
  content: '';
  position: absolute;
  bottom: 0;
  right: 0;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid white;
}

.user-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 4px;
}

.user-name {
  font-weight: 500;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.user-status-tag {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  white-space: nowrap;
  flex-shrink: 0;
}

.user-status-tag.waiting {
  background: #fff3e0;
  color: #ff9800;
}

.user-status-tag.serving {
  background: #e8f5e9;
  color: #4caf50;
}

.user-last-message {
  font-size: 12px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 2px;
}

.user-last-time {
  font-size: 11px;
  color: #999;
}

.avatar-status {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid white;
}

.avatar-status.online {
  background: #4caf50;
}

.unread-badge {
  background: #f44336;
  color: white;
  border-radius: 10px;
  padding: 2px 6px;
  font-size: 12px;
  min-width: 18px;
  text-align: center;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 16px 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.header-info {
  flex: 1;
  min-width: 0;
}

.header-title-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 6px;
}

.header-info h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-status {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-dot-small {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
  flex-shrink: 0;
}

.status-dot-small.online {
  background: #4caf50;
  box-shadow: 0 0 4px rgba(76, 175, 80, 0.5);
}

.status-dot-small.waiting {
  background: #ff9800;
  box-shadow: 0 0 4px rgba(255, 152, 0, 0.5);
}

.status-text {
  font-size: 12px;
  color: #666;
}

.status-text.online-text {
  color: #4caf50;
}

.status-text.waiting-text {
  color: #ff9800;
}

.header-meta {
  display: flex;
  gap: 12px;
  margin-top: 4px;
}

.meta-item {
  font-size: 11px;
  color: #999;
  font-family: 'Courier New', monospace;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.kefu-badge {
  padding: 6px 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
  display: flex;
  align-items: center;
  gap: 6px;
}

.badge-icon {
  font-size: 14px;
}

.btn-assign {
  padding: 8px 16px;
  background: #2196f3;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
  box-shadow: 0 2px 4px rgba(33, 150, 243, 0.2);
}

.btn-assign:hover {
  background: #1976d2;
  box-shadow: 0 2px 8px rgba(33, 150, 243, 0.3);
  transform: translateY(-1px);
}

.btn-delete {
  padding: 8px 16px;
  background: #f44336;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
  box-shadow: 0 2px 4px rgba(244, 67, 54, 0.2);
  margin-left: 8px;
}

.btn-delete:hover {
  background: #d32f2f;
  box-shadow: 0 2px 8px rgba(244, 67, 54, 0.3);
  transform: translateY(-1px);
}

.btn-icon {
  font-size: 14px;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background: #f5f5f5;
}

.message-item {
  margin-bottom: 16px;
  display: flex;
}

.message-sent {
  justify-content: flex-end;
}

.message-received {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 10px 14px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.message-sent .message-content {
  background: #2196f3;
  color: white;
}

.message-text {
  word-wrap: break-word;
  margin-bottom: 4px;
}

.message-time {
  font-size: 11px;
  color: #999;
  text-align: right;
}

.message-sent .message-time {
  color: rgba(255,255,255,0.8);
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  gap: 8px;
  background: white;
}

.chat-input input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  outline: none;
}

.chat-input input:focus {
  border-color: #2196f3;
}

.chat-input button {
  padding: 10px 24px;
  background: #2196f3;
  color: white;
  border: none;
  border-radius: 20px;
  cursor: pointer;
}

.chat-input button:hover:not(:disabled) {
  background: #1976d2;
}

.chat-input button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.chat-status {
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-online, .status-offline {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.status-online {
  background: #4caf50;
}

.status-offline {
  background: #999;
}

/* 房间信息卡片 */
.room-info-card {
  padding: 16px;
  background: white;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-header h4 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.room-status {
  margin-top: 12px;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
}

.status-item.success {
  background: #e8f5e9;
  color: #2e7d32;
}

.status-item.waiting {
  background: #fff3e0;
  color: #ef6c00;
}

.status-icon {
  font-weight: bold;
  font-size: 16px;
}

.reconnect-tip {
  margin-top: 12px;
  padding: 12px;
  background: #f5f5f5;
  border-radius: 6px;
  font-size: 13px;
  color: #666;
}

.reconnect-tip p {
  margin: 0;
}

/* 空状态样式 */
.empty-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
}

.empty-content p {
  font-size: 16px;
  margin: 0;
}

/* 头部状态样式 */
.header-status {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 4px;
}

.waiting-text {
  color: #ff9800;
  font-size: 12px;
}

.online-text {
  color: #4caf50;
  font-size: 12px;
}

/* 等待提示 */
.waiting-notice {
  margin-bottom: 8px;
  padding: 8px 12px;
  background: #fff3e0;
  border-radius: 6px;
  font-size: 12px;
  color: #ef6c00;
  text-align: center;
}

/* 客服输入提示 */
.kefu-input-notice {
  margin-bottom: 8px;
  padding: 8px 12px;
  background: #e8f5e9;
  border-radius: 6px;
  font-size: 12px;
  color: #2e7d32;
  text-align: center;
}
</style>

